import { Hono } from 'hono'
import { z } from 'zod'
import { PluginService } from '@/services/pluginService'
import { authMiddleware, getCurrentUserId } from '@/middleware/auth'
import { asyncHandler, ValidationError } from '@/middleware/errorHandler'

const developer = new Hono()
const pluginService = new PluginService()

// 所有开发者路由都需要认证
developer.use('*', authMiddleware())

// 验证模式
const createPluginSchema = z.object({
  name: z.string().min(1).max(100),
  displayName: z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  category: z.string().min(1),
  repositoryUrl: z.string().url().optional(),
  homepageUrl: z.string().url().optional(),
  documentationUrl: z.string().url().optional(),
  license: z.string().max(50).optional(),
  keywords: z.array(z.string()).max(20).optional(),
  tags: z.array(z.string()).max(10).optional()
})

const updatePluginSchema = z.object({
  displayName: z.string().min(1).max(100).optional(),
  description: z.string().max(500).optional(),
  repositoryUrl: z.string().url().optional(),
  homepageUrl: z.string().url().optional(),
  documentationUrl: z.string().url().optional(),
  license: z.string().max(50).optional(),
  keywords: z.array(z.string()).max(20).optional(),
  tags: z.array(z.string()).max(10).optional()
})

// 简单的验证中间件
const validateJson = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const body = await c.req.json()
      const validatedData = schema.parse(body)
      c.set('validatedData', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError('Validation failed', error.errors)
      }
      throw error
    }
  }
}

// 获取我的插件列表
developer.get('/plugins', asyncHandler(async (c) => {
  const userId = getCurrentUserId(c)!
  const page = parseInt(c.req.query('page') || '1')
  const limit = parseInt(c.req.query('limit') || '20')
  const status = c.req.query('status') || 'all'
  const search = c.req.query('search')

  const result = await pluginService.getDeveloperPlugins(userId, {
    page,
    limit,
    status,
    search
  })

  return c.json({
    success: true,
    data: result,
    message: 'My plugins retrieved successfully'
  })
}))

// 创建新插件
developer.post('/plugins',
  validateJson(createPluginSchema),
  asyncHandler(async (c) => {
    const userId = getCurrentUserId(c)!
    const data = c.get('validatedData')

    const plugin = await pluginService.createPlugin(userId, data)

    return c.json({
      success: true,
      data: { plugin },
      message: 'Plugin created successfully'
    }, 201)
  })
)

// 获取插件详情
developer.get('/plugins/:id', asyncHandler(async (c) => {
  const pluginId = c.req.param('id')
  const userId = getCurrentUserId(c)!

  const plugin = await pluginService.getDeveloperPlugin(userId, pluginId)

  return c.json({
    success: true,
    data: { plugin },
    message: 'Plugin details retrieved successfully'
  })
}))

// 更新插件信息
developer.put('/plugins/:id',
  validateJson(updatePluginSchema),
  asyncHandler(async (c) => {
    const pluginId = c.req.param('id')
    const userId = getCurrentUserId(c)!
    const data = c.get('validatedData')

    const plugin = await pluginService.updatePlugin(userId, pluginId, data)

    return c.json({
      success: true,
      data: { plugin },
      message: 'Plugin updated successfully'
    })
  })
)

// 删除插件
developer.delete('/plugins/:id', asyncHandler(async (c) => {
  const pluginId = c.req.param('id')
  const userId = getCurrentUserId(c)!

  await pluginService.deletePlugin(userId, pluginId)

  return c.json({
    success: true,
    message: 'Plugin deleted successfully'
  })
}))

// 上传新版本
developer.post('/plugins/:id/versions',
  asyncHandler(async (c) => {
    const pluginId = c.req.param('id')
    const userId = getCurrentUserId(c)!

    try {
      const body = await c.req.parseBody()

      // 获取上传的文件
      const file = body['file'] as File
      if (!file) {
        throw new ValidationError('Plugin file is required')
      }

      // 获取版本信息
      const version = body['version'] as string
      const changelog = body['changelog'] as string

      if (!version) {
        throw new ValidationError('Version is required')
      }

      // 将File转换为Buffer
      const fileBuffer = Buffer.from(await file.arrayBuffer())

      // 上传版本
      const versionData = await pluginService.uploadVersion(pluginId, userId, {
        version,
        changelog,
        fileBuffer,
        originalFileName: file.name,
        mimetype: file.type
      })

      return c.json({
        success: true,
        data: { version: versionData },
        message: 'Plugin version uploaded successfully'
      }, 201)
    } catch (error) {
      if (error instanceof ValidationError) {
        throw error
      }
      console.error('❌ Version upload error:', error)
      throw new ValidationError('Failed to upload plugin version')
    }
  })
)

export default developer
